// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// v [email]  rhymelph@gmail.com
// T [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/http_service/http_contact_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/provider/dashboard/expense/new_expense_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/add_business_contact_bottom_sheet.dart';
import 'package:flutter/material.dart';

class BusinessContactsProvider extends BaseProvider<List<BusinessContactEntity>>
    with SearchDataListMixin, FormatGroupMapLocalMixin<BusinessContactEntity> {
  BusinessContactEntity currentSelectContact;

  @override
  void initState() {
    super.initState();
  }

  @override
  Future get dataFuture => HttpContactService.contactList(1);

  void onShowAddBusiness() {
    unFocus();
    final expensePro = Providers.get<NewExpenseProvider>(
        RouterGenProviders.newExpensePage, null);
    String name;
    if (expensePro != null) {
      name = expensePro.businessName;
      data.forEach((element) {
        if (element.name == name) {
          name = null;
        }
      });
    }
    obtainContext?.call((context) async {
      final resultData =
          await showAddBusinessContactBottomSheet(context, defaultName: name);
      if (resultData != null) {
        BusinessContactEntity value;
        await post(HttpContactService.createContact(name: resultData),
            autoHandler: AutoHandler.Toast,
            loadingTip: S.current.loading, onSuccess: (data) {
          value = getEntityFromResult<BusinessContactEntity>(data);
        });
        if (value != null) {
          data.add(value);
          transformData(data, false);
          onSelectContact(value);
        }
      }
    });
  }

  void onSelectContact(BusinessContactEntity value) {
    currentSelectContact = value;
    update();
    obtainContext?.call((context) {
      Navigator.of(context).pop(value);
    });
  }

  void onAddBusiness() async {
    unFocus();
    BusinessContactEntity value;
    await post(HttpContactService.createContact(name: searchController.text),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (data) {
      value = getEntityFromResult<BusinessContactEntity>(data);
    });
    if (value != null) {
      data.add(value);
      transformData(data, false);
      onSelectContact(value);
    }
  }

  @override
  FutureOr<List<BusinessContactEntity>> transformData(
      List<BusinessContactEntity> d, bool isCache) {
    groupMap.clear();
    contactToMap(d);
    return d;
  }

  void contactToMap(List<BusinessContactEntity> contacts) {
    sortGroupToMap(contacts,
        sort: (a, b) => sortNameFirst(a, b, (t) => t.name),
        group: (a) => groupFirstName(a, (t) => t.name),
        filter: (a) => onFilterSearch(searchController.text, a.name),
        itemBefore: (map, b) => favoriteBefore(map, b, (b) => b.isFavorite));
    if (groupMap['Favourites'] != null && groupMap['Favourites'].length == 0) {
      groupMap.remove('Favourites');
    }
  }

  void onSelectBusinessContact(BusinessContactEntity data) {
    if (currentSelectContact == data) return;
    onSelectContact(data);
  }

  @override
  void searchRefreshData(searchData) {
    transformData(data, false);
    update();
  }
}
